<template>
  <div style="height: 100%;position: relative;">
    <div class="bim-operation">
      <!--<el-button type="primary" size="mini" style="margin-left: 10px" @click="getRooms()">房间</el-button>-->
      <!--<el-button type="primary" size="mini" style="margin-left: 10px" @click="getFloors()">楼层</el-button>-->
      <el-select v-model="process_id" size="mini" class="custom-select" placeholder="请选择工序" style="width: 150px;" clearable @change="processChange">
        <el-option
          class="custom-option"
          v-for="item in processList"
          :key="item.process_id"
          :label="item.process_name"
          :value="item.process_id"
        >
          <div class="select-label">{{ item.process_name }}</div>
        </el-option>
      </el-select>
      <el-select v-model="state_id" placeholder="请选择标签（问题）状态" size="mini" style="width: 100px;margin-right: 10px;" clearable @change="stateChange">
        <el-option
          class="custom-option"
          v-for="item in stateList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-input v-model="viewToken" @keyup.enter.native="viewTokenInput" size="mini" clearable placeholder="输入模型 viewToken" style="width: 300px;" />
      <el-button type="primary" size="mini" style="margin-left: 10px" @click="switchModel" v-if="viewTokens.length > 0">切换模型</el-button>
      <el-button type="primary" size="mini" style="margin-left: 10px" v-if="viewTokenIndex === 0" @click="add3DMarkerListener">新增标签</el-button>
      <el-button type="primary" size="mini" style="margin-left: 10px" v-if="viewTokenIndex === 0" @click="showMarketHandle">{{ showMarket ? '隐藏' : '显示' }}标签</el-button>
      <!--<el-button type="primary" size="mini" style="margin-left: 10px" @click="getCurrentModelState">获取模型状态</el-button>-->
      <!--<el-button type="primary" size="mini" style="margin-left: 10px" @click="setModelState">恢复模型状态</el-button>-->
      <!--<el-button type="primary" size="mini" style="margin-left: 10px" @click="blink">{{ this.isBlinkComponentsActivated ? '关闭' : '开启' }}强调</el-button>-->
      <!--<el-button type="primary" size="mini" style="margin-left: 10px" @click="isolateComponentsByData">{{ this.isIsolateComponentsByDataActivated ? '关闭' : '开启' }}隔离</el-button>-->
    </div>
    <div class="component-defail" v-if="showInfo">
      <div class="close">
        <i class="el-icon-error" @click="showInfo=false" />
      </div>
      <div class="defail-content">
        <div class="component-title">
          <span>{{ detail.code }}</span>
        </div>
        <div class="detail">
          <div><span>部位</span><span>{{ detail.bench }}</span></div>
          <div><span>状态</span><span>{{ detail.remark }}</span></div>
          <div><span>检查项</span><span>{{ detail.standard }}</span></div>
          <div><span>问题描述</span><span>{{ detail.position }}</span></div>
          <div><span>补充说明</span><span>{{ detail.height }}</span></div>
          <div><span>问题原因</span><span>{{ detail.level }}</span></div>
          <div><span>紧急程度</span><span>{{ detail.checkLevel }}</span></div>
          <div><span>承建商</span><span>{{ detail.assessLevel }}</span></div>
          <div><span>负责人</span><span>{{ detail.date }}</span></div>
          <div><span>整改人</span><span>{{ detail.imageCode }}</span></div>
          <div><span>登记时间</span><span>{{ detail.inspector }}</span></div>
          <div><span>登记人</span><span>{{ detail.register }}</span></div>
        </div>
      </div>
    </div>
    <el-button type="info" size="mini" circle :icon=" showTable ? 'el-icon-arrow-left' : 'el-icon-arrow-right'" @click="showTableHandler" class="show-table" />
    <div class="table-bim">
      <el-table
        :data="infos"
        class="problem-table"
        v-if="showTable"
      >
        <el-table-column
          align="center"
          prop="process"
          label="工序"
        />
        <el-table-column
          align="center"
          label="状态"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.state }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="handler"
          label="上报人"
        />
        <el-table-column
          align="center"
          prop="time"
          label="上报时间"
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-place" @click="positionNavigate(scope.$index)">位置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div id="view">
        <div class="state-list">
          <div v-for="state in stateList" :key="state.name" class="state-item"><span :style="{ backgroundColor: state.color }" /><span>{{ state.name }}</span></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import axios from 'axios'
import util from '@/utils'
import { markerWorldPositons, processList, stateList, stateIcon, infos, modelStateList, detail, viewTokens, viewTokenUrl } from './bimData'
let app = null
let viewer3D = null
let model3D = null
let marker3DContainer = null
// 配置标签常量
let drawableContainer = null // 二维标签容器
let clusterItem = null  // 聚合标签

export default {
  name: 'BimProcess',
  data() {
    return {
      processList: processList,
      process_id: '',
      state_id: 1,
      stateObj: stateList[1],
      bimObjData: {},
      stateList: stateList,
      componentIds: [],
      infos: infos,
      detail: detail,
      showInfo: false,
      viewTokens: viewTokens,
      viewTokenIndex: 0,
      sessionViewTokens: [],
      viewToken: '',
      conditions: [],
      isAddMarkerActivated: false, // 添加标签状态激活
      showMarket: true, // 显示标签
      showTable: true,
      markerWorldPositons: markerWorldPositons, // 标签位置列表
      modelStateList: modelStateList, // 模型状态列表
      modelState: {},
      isBlinkComponentsActivated: false,
      isIsolateComponentsByDataActivated: false
    }
  },

  // watch: {
  //   $route: {
  //     handler() {
  //       if (app) {
  //         app.destroy()
  //         app = null
  //       }
  //       this.init()
  //     },
  //     deep: true
  //   }
  // },

  mounted() { // 初始化
    const sessionTokens = sessionStorage.getItem('sessionViewTokens')
    if (sessionTokens) {
      this.sessionViewTokens = JSON.parse(sessionTokens)
      this.sessionViewTokens.forEach((token,index) => {
        if (token) {
          viewTokens.splice(index, 1, token)
        }
      })
    } else {
      this.sessionViewTokens = new Array(viewTokens.length)
    }
    this.viewToken = viewTokens[this.viewTokenIndex]
    this.init()
    // this.getViewTokenByFileId()
    window.onresize = () => {
      return (() => {
        // this.viewer3DResize()
      })()
    }
  },

  beforeDestroy() {
    if (app) {
      app.destroy()
      app = null
    }
  },
  methods: {
    // 获取分区-房间信息
    getRooms() {
      viewer3D.getModel().getAreas(function(data) {
        if (data) {
          console.log(data)
        }
      })
    },
    // 楼层操作
    getFloors() {
      let floorList = []
      let direction = { x: 1, y: 1, z: 1 };
      viewer3D.getFloors(function (data) {
        console.log(data)
        if (!data) {
          console.log('No floor data.');
          return;
        }
        for (let i = 0; i < data.length; i++) {
          floorList.push(data[i].id);
        }
        model3D.setFloorExplosion(3, floorList, direction);
        viewer3D.render();
      });
    },
    init () {
      this.initBIMFace()
    },
    viewTokenInput() {
      viewTokens.splice(this.viewTokenIndex, 1, this.viewToken)
      this.sessionViewTokens.splice(this.viewTokenIndex, 1, this.viewToken)
      sessionStorage.setItem('sessionViewTokens', JSON.stringify(this.sessionViewTokens))
      this.initBIMFace()
    },
    switchModel() {
      this.viewTokenIndex += 1
      if (this.viewTokenIndex >= viewTokens.length) {
        this.viewTokenIndex = 0
      }
      this.modelStateList = modelStateList // 模型状态列表
      this.viewToken = viewTokens[this.viewTokenIndex]
      this.initBIMFace()
    },
    getCondition(data) {
      if(data.condition){
        // 定义筛选条件
        let condition = data.condition;
        let objectData = condition.objectData;
        console.log(objectData)
        //定义颜色
        let color = new Glodon.Web.Graphics.Color("#4b50d3", 1);
        //根据条件对构件线框着色
        model3D.overrideComponentsFrameColor(condition, color);
      }
    },
    showTableHandler() {
      this.showTable = !this.showTable
      // this.viewer3DResize()
      // this.$nextTick(() => {
      //   viewer3D.render()
      // })
    },
    viewer3DResize() {
      this.$nextTick(() => {
        const elementDom = document.getElementById('view')
        viewer3D.resize(elementDom.offsetWidth, elementDom.offsetWidth)
      })
    },
    positionNavigate(index) {
      const indexNum = index % this.modelStateList.length
      const state = JSON.parse(this.modelStateList[indexNum].state)
      viewer3D.setState(state)
      viewer3D.render()
    },
    getCurrentModelState() {
      this.modelState = viewer3D.getCurrentState()
      this.$message.info('获取模型状态')
      this.modelStateList.push({ state: JSON.stringify(this.modelState) })
    },
    setModelState() {
      if(!this.modelState){
        this.$message.warning('请先获取获取视图状态')
      }else{
        // 恢复模型状态
        viewer3D.setState(this.modelState);
        viewer3D.render();
      }
    },
    showMarketHandle() {
      if (this.showMarket) {
        marker3DContainer.hideAllItems()
      } else {
        marker3DContainer.showAllItems()
      }
      this.showMarket = !this.showMarket
    },
    processChange() {
      for (let i = 0; i < this.processList.length; i++) {
        if (this.processList[i].process_id == this.process_id) {
          this.conditions = this.processList[i].conditions
          break
        }
      }
      if (app && model3D) {
        model3D.clearOverrideColorComponents()
        if (this.process_id) {
          this.renderWeldingLime()
        }
      } else {
        app.destroy()
        app = null
        this.initBIMFace()
      }
    },
    stateChange() {
      for (let i = 0; i < this.stateList.length; i++) {
        if (this.stateList[i].id == this.state_id) {
          this.stateObj = this.stateList[i]
          break
        }
      }
      if (this.state_id) {
        const allItems = marker3DContainer.getAllItems()
        if (allItems.length > 0) {
          allItems.forEach(markerItem => {
            markerItem.setSrc(stateIcon[this.stateObj.icon])
          })
        }
      }
    },
    //  是否监听 模型单击事件
    add3DMarkerListener() {
      const body = document.querySelector("body")
      if (this.isAddMarkerActivated) {
        // 取消点击事件监听
        viewer3D.removeEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.MouseClicked, this.addCustomItem);
        body.style.cursor= "auto"
      } else {
        // 添加点击监听事件，创建三维标签
        viewer3D.addEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.MouseClicked, this.addCustomItem);
        body.style.cursor= "crosshair"
      }
      this.isAddMarkerActivated = !this.isAddMarkerActivated;
      viewer3D.render();
    },

    getViewTokenByFileId() {
      axios({
        url: '/bimface/oauth2/token',
        method: 'post',
        headers: {
          Authorization: 'Basic S0twSXdTY1UwaGY5cFAzVkxscE43VTM3QlBCREhrWWw6elNnTEZmTXYxUDRJaE5yS1JFcUpqUXBDZmVhRVpTRUQ='
        }
      }).then((res) => {
        const accessToken = res.data.data.token
        axios({
          url: '/bimface/view/token',
          method: 'get',
          params: {
            fileId: '10000790815545'
          },
          headers: {
            Authorization: `Bearer ${accessToken}`
          }
        }).then(response => {
          if (response.data.code === 'success') {
            this.viewToken = response.data.data
            viewTokens.splice(0, 1, this.viewToken)
          }
        }).finally(() => {
          this.viewToken = viewTokens[this.viewTokenIndex]
          this.initBIMFace()
        })
      })
    },

    // 渲染焊缝
    renderWeldingLime () {
      // 从viewer3D对象中获取模型对象model3D
      const self = this
      if (!model3D) {
        model3D = viewer3D.getModel()
      }
      if (self.conditions.length < 1) return
      model3D.getComponentsByConditions(self.conditions, function (ids) {
        self.componentIds = [...ids]
        for (let i = 0; i < ids.length; i++) {
          const index = i % 4
          const color = new Glodon.Web.Graphics.Color(self.stateList[index].color, 0.8)
          model3D.overrideComponentsColorById([ids[i]], color)
        }
        viewer3D.render()
      }, function () {
        self.$message.error('获取焊缝构件失败!')
      })
    },

    // 单击增加标签
    addCustomItem(objectData) {
      console.log(objectData)
      if (!objectData || !objectData.worldPosition) {
        this.$message.info('请选择模式适合位置')
        return
      }
      const position = objectData.worldPosition;
      this.markerWorldPositons.push(position)
      let marker3dConfig = new Glodon.Bimface.Plugins.Marker3D.Marker3DConfig();
      marker3dConfig.src = stateIcon[this.stateObj.icon]
      marker3dConfig.worldPosition = position;
      //三维标签的提示
      marker3dConfig.tooltip = "This is 3DMarker.";
      let marker3d = new Glodon.Bimface.Plugins.Marker3D.Marker3D(marker3dConfig);
      marker3DContainer.addItem(marker3d);
      this.add3DMarkerListener() // 标签添加成功 移除单击事件
      viewer3D.clearSelectedComponents();
      viewer3D.render();
    },
    // 创建聚合标签容器
    createClusterItem() {
      // 构造聚合标签容器配置项
      let clusterContainerConfig = new Glodon.Bimface.Plugins.Cluster.ClusterContainerConfig();
      clusterContainerConfig.viewer = viewer3D;
      // 构造聚合标签容器
      let clusterContainer = new Glodon.Bimface.Plugins.Cluster.ClusterContainer(clusterContainerConfig);
      // 构造聚合标签配置项
      let clusterItemConfig = new Glodon.Bimface.Plugins.Cluster.ClusterItemConfig();
      // clusterItemConfig.tags = drawableContainer.getAllItems();
      clusterItemConfig.tags = marker3DContainer.getAllItems();
      console.log(marker3DContainer.getAllItems().length);
      clusterItemConfig.maxLevel = 8;
      clusterItemConfig.viewer = viewer3D;
      // 构造聚合标签对象
      clusterItem = new Glodon.Bimface.Plugins.Cluster.ClusterItem(clusterItemConfig);
      // 定义聚合标签的点击事件
      clusterItem.onClick(function (data) {
        let boundingBox = data.boundingBox;
        viewer3D.zoomToBoundingBox(boundingBox, 5);
      });
      clusterContainer.addCluster(clusterItem);
      clusterContainer.update();
    },
    // 初始化增加标签
    initAddCustomItem (positions = []) {
      for (let i = 0; i < positions.length; i++) {
        let marker3dConfig = new Glodon.Bimface.Plugins.Marker3D.Marker3DConfig();
        marker3dConfig.src = stateIcon[this.stateObj.icon]
        marker3dConfig.worldPosition = positions[i];
        //三维标签的提示
        marker3dConfig.tooltip = "This is 3DMarker.";
        let marker3d = new Glodon.Bimface.Plugins.Marker3D.Marker3D(marker3dConfig);
        marker3d.onClick(this.onMarkerClick)
        marker3DContainer.addItem(marker3d);
      }
      viewer3D.render()
    },
    onMarkerClick() {
      this.showInfo = true
    },
    stateTableChange(row) {
      row.handler = '合诚检测'
      row.time = util.formatDate.format(new Date(), 'yyyy-MM-dd')
    },
    // bim 模型初始化
    initBIMFace() {
      const self = this
      if (!self.viewToken) return
      if (app) {
        app.destroy()
        app = null
      }
      // 创建BimfaceSDKLoaderConfig
      const loaderConfig = new BimfaceSDKLoaderConfig()
      // 设置BimfaceSDKLoaderConfig的viewToken
      loaderConfig.viewToken = self.viewToken
      // 调用BimfaceSDKLoader的load方法加载模型
      BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback)
      // 加载成功回调函数
      function successCallback(viewMetaData) {
        // 获取DOM元素
        const domShow = document.getElementById('view')
        // 创建WebApplication3DConfig
        const webAppConfig = new Glodon.Bimface.Application.WebApplication3DConfig()
        // 设置创建WebApplication3DConfig的dom元素值
        webAppConfig.domElement = domShow
        // 创建WebApplication3D
        app = new Glodon.Bimface.Application.WebApplication3D(webAppConfig)
        // 添加构件树节点点击监听事件
        // app.addEventListener(Glodon.Bimface.Application.WebApplication3DEvent.ModelTreeNodeClicked, self.getCondition)
        // 添加待显示的模型
        app.addView(self.viewToken)
        // 获取viewer3D对象
        viewer3D = app.getViewer()
        // 渐变3d背景色
        const color1 = new Glodon.Web.Graphics.Color('#001321', 0.4)
        const color2 = new Glodon.Web.Graphics.Color('#00273C', 0.1)
        viewer3D.setBackgroundColor(color1, color2)

        viewer3D.addEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.ModelAdded, function (data) {
          // 从viewer3D对象中获取模型对象model3D
          const model3D = viewer3D.getModel(data)
          // model3D.setModelScale({ x: 0, y: 0, z: 0 }, 2);
          viewer3D.render()
        })

        // 场景加载完成触发
        viewer3D.addEventListener(Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded, function () {
          self.renderWeldingLime()

          // 引线标签的顶点
          // 初始化DrawableContainer
          const drawableConfig = new Glodon.Bimface.Plugins.Drawable.DrawableContainerConfig()
          drawableConfig.viewer = viewer3D
          drawableContainer = new Glodon.Bimface.Plugins.Drawable.DrawableContainer(drawableConfig)
          //三维标签的配置类
          let markerConfig = new Glodon.Bimface.Plugins.Marker3D.Marker3DContainerConfig();
          markerConfig.viewer = viewer3D;
          marker3DContainer = new Glodon.Bimface.Plugins.Marker3D.Marker3DContainer(markerConfig);
          self.initAddCustomItem(self.markerWorldPositons)
          self.createClusterItem()
          viewer3D.render()
        })
      }

      // 加载失败回调函数
      function failureCallback(error) {
        self.$confirm('模型viewToken过期，请重新获取viewToken,并输入新viewToken。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.viewToken = ''
          if (viewTokenUrl[self.viewTokenIndex]) {
            window.open(viewTokenUrl[self.viewTokenIndex], '_blank');
          }
        }).catch(() => {

        });
      }
    },
    // 强调效果
    blink() {
      if (!this.isBlinkComponentsActivated) {
        // 构件闪烁
        viewer3D.addBlinkComponentsById(['1866578', '1876628', '1866578']);
        viewer3D.setBlinkColor(new Glodon.Web.Graphics.Color("#32D3A6", 0.8));
        viewer3D.enableBlinkComponents(true);
        viewer3D.setBlinkIntervalTime(500);
        viewer3D.render();
      } else {
        // 取消闪烁
        viewer3D.clearAllBlinkComponents();
        viewer3D.render();
      }
      this.isBlinkComponentsActivated = !this.isBlinkComponentsActivated;
    },
    // 构件隔离
    isolateComponentsByData() {
      if (!this.isIsolateComponentsByDataActivated) {
        const makeOthersTranslucent = Glodon.Bimface.Viewer.IsolateOption.MakeOthersTranslucent
        //设置隔离构件的条件
        const conditions = [
          {familyType: '钢筋混凝土地墙-900'},
          {familyType: '钢筋混凝土地墙-800'}
          // {levelName: '底板顶面（-2.898（黄海-14.817））'}
          // {floor: '底板顶面（-2.898（黄海-14.817））'} // 使用levelName
          // {categoryId: '-2000011'}
          // {categoryName: '墙'} //  不可用 (在获取构件上可用)
          // {family: '基本墙'}
          // {familyId: 0} // 不可用
          // {familyType: '钢筋混凝土地墙-900'}
          // {familyTypeId: '1801095'} // 不可用
        ]
        model3D.isolateComponentsByObjectData(conditions, makeOthersTranslucent);
        viewer3D.render();
      } else {
        //取消隔离
        model3D.clearIsolation();
        viewer3D.render();
      }
      this.isIsolateComponentsByDataActivated = !this.isIsolateComponentsByDataActivated;
    }

  }
}
</script>

<style scoped lang='scss'>

  .component-defail {
    position: absolute;
    top: 12%;
    left: 26%;
    z-index: 10;
    width: 540px;
    border: 1px solid #409EFF ;
    border-radius: 10px;
    background-color: white;
    padding-bottom: 10px;
    .close {
      position: relative;
      .el-icon-error {
        cursor: pointer;
        position: absolute;
        top: 10px;
        right: 10px;
      }
    }
    .defail-content {
      height: 400px;
      overflow-y: auto;
    }
    .component-title {
      height: 60px;
      line-height: 40px;
      padding: 14px 10px 0 18px;
    }
    .process-table {
      border-radius: 0 0 10px 10px;
    }
    .detail {
      display: flex;
      flex-wrap: wrap;
      padding-bottom: 10px;
      div {
        height: 50px;
        padding: 10px 10px 10px 20px;
        span:nth-child(1) {
          display: inline-block;
          width: 100px;
          text-align: right;
        }
        span:nth-child(2) {
          margin-left: 10px;
          background-color: rgba(210, 231, 254, 0.47);
          padding: 10px;
          display: inline-block;
          min-width: 120px;
          text-align: left;
          border-radius: 2px;
        }
      }
    }
  }
  .show-table {
    position: absolute;
    top: 84px;
    left: -13px;
    z-index: 10000;
  }
  .table-bim {
    display: flex;
    height: calc(100% - 60px);
    .problem-table {
      flex: 1;
    }
    #view {
      height: 100%;
      flex: 1;
      text-align: left;
      position: relative;
      .state-list {
        font-size: 12px;
        display: flex;
        position: absolute;
        left: 200px;
        top: 20px ;
        .state-item {
          height: 26px;
          margin-left: 20px;
          span:nth-child(1) {
            display: inline-block;
            height: 10px;
            width: 10px;
            border-radius: 50%;
            margin-right: 10px;
          }
        }
      }
    }
  }

  .bim-operation {
    display: flex;
    align-items: center;
    margin: 10px;
    .custom-select {
      width: 300px;
      margin-right: 10px;
    }
    .select-label {

    }
  }
  .noexist_divece {
    position: absolute;
    z-index: 999;
    // background-color: #000;
    // position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #041623;
    &>.noexist_divece_box {
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      flex-direction: column;
      opacity: .8;
      img {
        height: 120px;
        width: 120px;
        margin-right: 10px;
        object-fit: contain;
        margin-bottom: 1px;
      }
      h1 {
        margin-bottom: 16px;
        font-size: 21px;
        font-weight: 500;
      }
      p {
        font-size: 16px;
        margin-bottom: 29px;
      }
      a {
        text-decoration: underline;
        color:#00adff;
        font-size: 24px;
      }
    }
  }
</style>
<style lang="scss">
  .custom-option.el-select-dropdown__item{
    height: auto;
    .select-label {
      max-width: 400px;
      word-break: break-all;
      white-space: pre-wrap;
      line-height: 20px;
      padding: 6px 0;
    }
  }
</style>
